from bluetooth import *
from time import sleep


DEVICES = {'68:EB:AE:68:02:0E': {'device_name': 'sueastside', 'online': False, 'nick': 'sueastside'},
           '00:23:B4:17:63:92': {'device_name': 'Inspector Morse', 'online': False, 'nick': 'moeder'},}

def SendEvent(event, arg):
    try:
        import Pyro.core
        house = Pyro.core.getProxyForURI("PYRONAME://house")
        house.Fire(event, arg)
    except Pyro.errors.NamingError as e:
        print e

def save_lookup_name(address):
    try:
        return lookup_name(address)
    except BluetoothError as e:
        print e

def save_discover_devices():
    try:
        return discover_devices()
    except BluetoothError as e:
        print e
        return []

def main():
    count = 0
    while True:
        count += 1
        for address in DEVICES:
            name = save_lookup_name(address)
            device_name = DEVICES[address]['device_name']
            nick_name = DEVICES[address]['nick']
            online = name == device_name
            if DEVICES[address]['online'] != online:
                DEVICES[address]['online'] = online
                if online:
                    SendEvent('location.entered', nick_name)
                else:
                    SendEvent('location.exited', nick_name)
            #elif online:
            #    print (nick_name, 'still here', online)
        #print 'ping', count
        #SendEvent('location.ping', count)
        if count > 10:
            count = 0
            for address in save_discover_devices():
                if address not in DEVICES:
                    SendEvent('location.entered.unknow', (address, save_lookup_name(address),))
                else:
                    print address, 'is discoverable, not very safe!'
        sleep(1)

if __name__=="__main__":
    try:
	    main()
    except BaseException as e:
        SendEvent('service.failure.bluetooth', e)
        raise e
